package com.example.service;

import com.example.pojo.MsslyyBook;
import com.example.pojo.MsslyyOrderDetail;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.MsslyyOrderDetailMapper;
import com.example.utils.DateUtil;
import com.example.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MsslyyOrderDetailService extends ServiceImpl<MsslyyOrderDetailMapper, MsslyyOrderDetail> {

    @Resource
    private MsslyyOrderDetailMapper msslyyOrderDetailMapper;
    @Resource
    private MsslyyBookService msslyyBookService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private DateUtil dateUtil;
    /**
     * 根据订单主表id增加多条订单详情
     * @param id 订单主表id
     * @param bookIds 全部商品的id
     * @param bookAmounts 全部商品的下单数量
     */
    public void addOrder(Long id, String bookIds,String bookAmounts){
        String[] ids = bookIds.split(",");
        String[] amounts = bookAmounts.split(",");
        //添加多条订单详情记录
        for (int i = 0; i < ids.length; i++) {
            MsslyyBook e = msslyyBookService.getById(ids[i]);
            MsslyyOrderDetail msslyyOrderDetail=new MsslyyOrderDetail();
            msslyyOrderDetail.setOrderMasterId(id);
            msslyyOrderDetail.setBookId(e.getId());
            msslyyOrderDetail.setBookTitle(e.getBookTitle());
            msslyyOrderDetail.setOrderDetailAmount(Integer.parseInt(amounts[i]));
            msslyyOrderDetail.setBookNewPrice(e.getBookNewPrice());
            save(msslyyOrderDetail);
            //设置凌晨失效
            long expireTime = (dateUtil.getEveryDayTime() - System.currentTimeMillis())/1000;
            //添加到今日销售量
            boolean sales = redisUtil.hasKey("sales");
            if (sales){
                redisUtil.incr("sales",Long.parseLong(amounts[i]));
            }else {
                redisUtil.set("sales",Integer.parseInt(amounts[i]),expireTime);
            }
        }


    }

}
